package com.geoai.uimap.core.osmdroid

import androidx.core.graphics.drawable.toDrawable
import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapMarker
import com.geoai.uimap.utils.GEOMapCacheUtils
import com.geoai.uimap.utils.getOsmMapView
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.overlay.Marker

class OsmMarker(private val map: IGEOMap) : GEOMapMarker() {
    private var marker: Marker? = null

    override fun show(): GEOMapMarker {
        val bitmap = GEOMapCacheUtils.getBitmapCache(map.getContext(), mImageResId)
        if (bitmap == null) {
            return this
        }
        val mapView = map.getOsmMapView()
        mapView?.let { mapView ->
            marker = Marker(mapView)
            marker?.position = GeoPoint(markerPoint?.latitude ?: 0.0, markerPoint?.longitude ?: 0.0)
            marker?.icon = bitmap.toDrawable(map.getContext().resources)
            mapView.overlayManager.add(marker)
            mapView.invalidate()
        }
        return this
    }

    override fun getMarkerId(): String {
        return marker?.id.toString()
    }

    override fun setRotateAngle(angel: Float): GEOMapMarker {
        marker?.rotation = angel
        return this
    }

    override fun destroy() {
        map.getOsmMapView()?.let {
            it.overlayManager.remove(marker)
            it.invalidate()
        }
    }


}